<template>
  <div class="event-management-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>赛事设置</span>
      </div>

      <el-form :model="eventForm" :rules="rules" ref="eventForm" label-width="120px">
        <!-- 基础信息 -->
        <el-form-item label="赛事名称：" prop="name">
          <el-input v-model="eventForm.name" placeholder="请输入" style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="开赛时间：" prop="timeRange">
          <el-date-picker
            v-model="eventForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 400px;"
          ></el-date-picker>
        </el-form-item>

        <!-- 投票规则 -->
        <el-form-item label="投票规则：">
          <div class="vote-rule">
            <span>每人每天最多可投</span>
            <el-input-number
              v-model="eventForm.voteLimitPerDay"
              :min="1"
              :max="100"
              style="margin: 0 10px;"
            ></el-input-number>
            <span>票，投票同一个参赛者限</span>
            <el-input-number
              v-model="eventForm.voteLimitPerParticipant"
              :min="1"
              :max="eventForm.voteLimitPerDay"
              style="margin: 0 10px;"
            ></el-input-number>
            <span>票/天</span>
          </div>
        </el-form-item>

        <!-- 练习题库 -->
<!--        <el-form-item label="练习题库：">-->
<!--          <el-select-->
<!--            v-model="eventForm.practiceBank"-->
<!--            filterable-->
<!--            remote-->
<!--            reserve-keyword-->
<!--            placeholder="搜索并选择"-->
<!--            :remote-method="searchQuestionBanks"-->
<!--            :loading="bankLoading"-->
<!--            style="width: 300px;"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="bank in questionBanks"-->
<!--              :key="bank.id"-->
<!--              :label="bank.name"-->
<!--              :value="bank.id"-->
<!--            >-->
<!--              <span style="float: left">{{ bank.name }}</span>-->
<!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ bank.major }}</span>-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <!-- 练习题库 -->
        <el-form-item label="练习题库：">
          <el-select
            v-model="eventForm.practiceBank"
            placeholder="请选择"
            style="width: 52%"
            multiple
            clearable
          >
            <el-option
              v-for="item in tiku"
              :key="item.btk_code"
              :label="item.btk_name"
              :value="item.btk_code">
            </el-option>
<!--            <el-option-->
<!--              v-for="item in tiku"-->
<!--              :key="item.btk_code"-->
<!--              :label="item.btk_name"-->
<!--              :value="item.btk_code"-->
<!--            ></el-option>-->
          </el-select>
        </el-form-item>

        <el-divider></el-divider>

        <!-- 模拟测试设置 -->
        <h4>模拟测试：
<!--          <u-switch v-model="eventForm.checked" active-color="red" inactive-color="#eee"></u-switch>-->
        </h4>
        <el-form-item label="时长：" prop="duration">
          <el-input-number
            v-model="eventForm.duration"
            :min="10"
            :max="300"
            :step="5"
          ></el-input-number>
          <span style="margin-left: 10px;">分钟</span>
        </el-form-item>

        <el-form-item label="题目与分值：">
          <p style="color: #909399; margin-top: -10px;">系统自动从赛事练习题库中抽取题目</p>

          <div class="question-settings">
            <el-checkbox v-model="eventForm.enableSingleChoice">单选题</el-checkbox>
            <span>共</span>
            <el-input-number
              v-model="eventForm.singleChoice.count"
              :min="0"
              :max="200"
              :disabled="!eventForm.enableSingleChoice"
            ></el-input-number>
            <span>题，每题</span>
            <el-input-number
              v-model="eventForm.singleChoice.score"
              :min="1"
              :max="10"
              :step="1"
              :disabled="!eventForm.enableSingleChoice"
            ></el-input-number>
            <span>分</span>
          </div>

          <div class="question-settings">
            <el-checkbox v-model="eventForm.enableTrueFalse">判断题</el-checkbox>
            <span>共</span>
            <el-input-number
              v-model="eventForm.trueFalse.count"
              :min="0"
              :max="100"
              :disabled="!eventForm.enableTrueFalse"
            ></el-input-number>
            <span>题，每题</span>
            <el-input-number
              v-model="eventForm.trueFalse.score"
              :min="1"
              :max="10"
              :step="1"
              :disabled="!eventForm.enableTrueFalse"
            ></el-input-number>
            <span>分</span>
          </div>

          <div class="question-settings">
            <el-checkbox v-model="eventForm.enableMultipleChoice">多选题</el-checkbox>
            <span>共</span>
            <el-input-number
              v-model="eventForm.multipleChoice.count"
              :min="0"
              :max="100"
              :disabled="!eventForm.enableMultipleChoice"
            ></el-input-number>
            <span>题，每题</span>
            <el-input-number
              v-model="eventForm.multipleChoice.score"
              :min="1"
              :max="10"
              :step="1"
              :disabled="!eventForm.enableMultipleChoice"
            ></el-input-number>
            <span>分</span>
          </div>

          <div class="question-settings">
            <el-checkbox v-model="eventForm.enableShortAnswer">简答题</el-checkbox>
            <span>共</span>
            <el-input-number
              v-model="eventForm.shortAnswer.count"
              :min="0"
              :max="50"
              :disabled="!eventForm.enableShortAnswer"
            ></el-input-number>
            <span>题，每题</span>
            <el-input-number
              v-model="eventForm.shortAnswer.score"
              :min="1"
              :max="20"
              :step="1"
              :disabled="!eventForm.enableShortAnswer"
            ></el-input-number>
            <span>分</span>
          </div>
        </el-form-item>

        <el-divider></el-divider>

        <!-- 封面图片上传 -->
        <el-form-item label="封面：" prop="coverImage">
<!--          <el-upload-->
<!--            class="cover-uploader"-->
<!--            action="/api/upload"-->
<!--            :show-file-list="false"-->
<!--            :on-success="handleCoverSuccess"-->
<!--            :before-upload="beforeCoverUpload"-->
<!--            :on-error="handleUploadError"-->
<!--          >-->
<!--            <img v-if="eventForm.coverImage" :src="eventForm.coverImage" class="cover-image">-->
<!--            <div v-else class="uploader-placeholder">-->
<!--              <i class="el-icon-plus"></i>-->
<!--              <div class="upload-tips">-->
<!--                <p>展示于列表和详情页</p>-->
<!--                <p>图片小于2M</p>-->
<!--                <p>建议上传16:9比例（如750x422px）的JPG/PNG/WebP格式</p>-->
<!--              </div>-->
<!--            </div>-->
<!--          </el-upload>-->
          <!--    头像-->
          <div>
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :on-change="changeavart"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="eventForm.coverImage" :src="eventForm.coverImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <div class="upload-tip">展示于列表和详情页。图片小于1M。
            建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
        </el-form-item>
        <!-- 赛事介绍 -->
        <el-form-item label="赛事介绍：" prop="user_phoneno" >
          <el-input
            v-model="eventForm.saishijieshao"
            placeholder="请输入"
            clearable
            type="textarea"
            rows="10"
          ></el-input>
        </el-form-item>
        <!-- 通知公告 -->
        <el-form-item label="通知公告：" prop="user_phoneno" >
          <el-input
            v-model="eventForm.tongzhigonggao"
            placeholder="请输入"
            clearable
            type="textarea"
            rows="10"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('eventForm')">保存</el-button>
          <el-button @click="resetForm('eventForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {createbjs, querybtklist, updatebjs, uploadres} from "../../api/InstitutionApi";
import { formatDate }  from '../../utils/util'
export default {
  data() {
    return {
      eventForm: {
        bjscode: '',
        name: '',  ////赛事名称
        timeRange: [], ////开赛时间段
        voteLimitPerDay: 10,  ////每天最多投票数
        voteLimitPerParticipant: 1, ////一个最多投票数
        practiceBank: [], ///题库
        duration: 90, ///时长
        checked: true,
        enableSingleChoice: true,
        singleChoice: {
          count: 80,
          score: 1
        },
        enableTrueFalse: true,
        trueFalse: {
          count: 10,
          score: 1
        },
        enableMultipleChoice: true,
        multipleChoice: {
          count: 10,
          score: 1
        },
        enableShortAnswer: true,
        shortAnswer: {
          count: 10,
          score: 1
        },
        coverImage: '',
        apiImgCode:'',
        saishijieshao: '',
        tongzhigonggao: ''
      },
      question:[],
      base64Data:'',
      imageUrl:'',
      // 题库
      tiku: [
        { id: 1, name: '模拟题库' },
        { id: 2, name: '实战题库' },
        { id: 3, name: '竞赛' },
        { id: 4, name: '练习' },
      ],
      //输入验证
      rules: {
        name: [
          { required: true, message: '请输入赛事名称', trigger: 'blur' }
        ],
        timeRange: [
          { required: true, message: '请设置开赛时间', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '请设置测试时长', trigger: 'blur' }
        ],
      },
      questionBanks: [],
      bankLoading: false,
      isEdit: false,  ////是否编辑
      jsrow:{} ///编辑时传回来的竞赛内容
    };
  },
  created() {
    // 加载题库
    this.getTkList()
    this.jsrow = this.$route.query.jsrow;
    if(this.jsrow) {
      this.isEdit = true
      // 将内容进行赋值
      this.getJsContent()
    } else {
      this.isEdit = false
    }
  },
  methods: {
    // 查询所有题库列表
    getTkList() {
      querybtklist().then(res => {
        this.tiku =[]
        this.tiku = res.data.base_info;
        console.log('获取所有题库列表：', res)
      })
    },
    // 将内容进行赋值
    getJsContent() {
      console.log('jsrow:',this.jsrow);
      this.eventForm.bjscode = this.jsrow.bjs_code
      this.eventForm.name = this.jsrow.bjs_name
      this.eventForm.timeRange.push(this.jsrow.bjs_startdate) ////开赛时间段
      this.eventForm.timeRange.push(this.jsrow.bjs_enddate) ////开赛时间段
      this.eventForm.voteLimitPerDay = this.jsrow.bjs_tpmax  ////每天最多投票数
      this.eventForm.voteLimitPerParticipant = this.jsrow.bjs_tponemax ////一个最多投票数
      this.eventForm.practiceBank = this.jseditGetFl(this.jsrow.tklist) ///题库
      this.eventForm.duration = this.jsrow.bjs_toltime ///时长
      this.eventForm.checked = this.jsrow.bjs_ismoni === 1 ? true : false
      this.eventForm.enableSingleChoice = this.jsrow.bjs_usedanxuan === 1 ? true : false
      this.eventForm.singleChoice = {
        count: 80,
        score: 1
      }
      this.eventForm.enableTrueFalse = this.jsrow.bjs_usepanduan === 1 ? true : false
      this.eventForm.trueFalse = {
        count: 10,
        score: 1
      }
      this.eventForm.enableMultipleChoice = this.jsrow.bjs_useduoxuan === 1 ? true : false
      this.eventForm.multipleChoice = {
        count: 10,
        score: 1
      }
      this.eventForm.enableShortAnswer = this.jsrow.bjs_usejianda === 1 ? true : false
      this.eventForm.shortAnswer = {
        count: 10,
        score: 1
      }
      this.eventForm.coverImage = this.jsrow.bjs_logo_uri[0].url
      this.eventForm.apiImgCode = this.jsrow.bjs_logo_uri[0].imguri
      this.eventForm.saishijieshao = this.jsrow.bjs_desc
      this.eventForm.tongzhigonggao = this.jsrow.bjs_tzgg

    },

    // 编辑时生成题库
    jseditGetFl(tkcode) {
      let tmptiku = []
      for(let i=0; i < tkcode.length; i++) {
        tmptiku.push(tkcode[i].btk_code)
      }
      return tmptiku
    },


    //头像
    // 头像上传
    // 自定义上传方法
    customUpload(params) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc":"课程图片"  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.eventForm.apiImgCode = res.data.base_info
      })

    },

    // 上传前将图片转为base64
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.eventForm.coverImage = reader.result; // 带前缀的完整Base64，可直接用于<img>显示

          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload()
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },

    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //头像结束
    // 提交表单
    submitForm(formName) {
      if(this.isEdit) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 这里提交表单数据到后端
            const formData = {
              ...this.eventForm,
              startTime: formatDate(this.eventForm.timeRange[0]),
              endTime: formatDate(this.eventForm.timeRange[1])
            };
            console.log('提交赛事设置:', formData);
            updatebjs({
              "bjscode": formData.bjscode, ////#竞赛code
              "bjsname": formData.name, //#竞赛名称
              "bjsstartdate": formData.startTime,//#开始时间
              "bjsenddate": formData.endTime,//#结束时间
              "bjstoltime": formData.duration,//#时长
              "bjstpmax": formData.voteLimitPerDay,//#最大提交次数
              "bjstponemax": formData.voteLimitPerParticipant,//#一次提交最大分数
              "bjstklist": formData.practiceBank,//#题库列表
              "bjsismoni": 1,//#是否模拟考试 0否，1是
              "bjsusedanxuan": formData.enableSingleChoice === true ? '1': '0',//#是否使用单选题
              "bjsdanxuan": formData.singleChoice.count,//#单选题数量
              "bjsdanxuanfenzhi": formData.singleChoice.score,//#单选题分数
              "bjsuseduoxuan": formData.enableMultipleChoice === true ? '1': '0',//#是否使用多选题
              "bjsduoxuan": formData.multipleChoice.count,//#多选题数量
              "bjsduoxuanfenzhi": formData.multipleChoice.score,//#多选题分数
              "bjsusepanduan": formData.enableTrueFalse === true? '1': '0',//#是否使用判断题
              "bjspanduan": formData.trueFalse.count,//#判断题数量
              "bjspanduanfenzhi": formData.trueFalse.score,//#判断题分数
              "bjsusejianda": formData.enableShortAnswer === true ? '1': '0',//#是否使用简答题
              "bjsjianda": formData.shortAnswer.count,//#简答题数量
              "bjsjiandafenzhi": formData.shortAnswer.score,//#简答题分数
              "bjslogo_uri": formData.apiImgCode,//#logo图片
              "bjsdesc": formData.saishijieshao,//#竞赛说明
              "bjstzgg": formData.tongzhigonggao,//#竞赛通知公告
            }).then(res => {
              console.log('赛事保存：',res);
              if(res.msg === '更新基础竞赛成功') {
                this.$router.push({
                  path: '/pro/index',
                  query: ''
                });
              } else {
                this.$message.success('赛事设置保存失败');
              }

            })

          } else {
            console.log('表单验证失败');
            return false;
          }
        });


      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 这里提交表单数据到后端
            const formData = {
              ...this.eventForm,
              startTime: formatDate(this.eventForm.timeRange[0]),
              endTime: formatDate(this.eventForm.timeRange[1])
            };
            console.log('提交赛事设置:', formData);
            createbjs({
              "bjsname": formData.name, //#竞赛名称
              "bjsstartdate": formData.startTime,//#开始时间
              "bjsenddate": formData.endTime,//#结束时间
              "bjstoltime": formData.duration,//#时长
              "bjstpmax": formData.voteLimitPerDay,//#最大提交次数
              "bjstponemax": formData.voteLimitPerParticipant,//#一次提交最大分数
              "bjstklist": formData.practiceBank,//#题库列表
              "bjsismoni": 1,//#是否模拟考试 0否，1是
              "bjsusedanxuan": formData.enableSingleChoice === true ? '1': '0',//#是否使用单选题
              "bjsdanxuan": formData.singleChoice.count,//#单选题数量
              "bjsdanxuanfenzhi": formData.singleChoice.score,//#单选题分数
              "bjsuseduoxuan": formData.enableMultipleChoice === true ? '1': '0',//#是否使用多选题
              "bjsduoxuan": formData.multipleChoice.count,//#多选题数量
              "bjsduoxuanfenzhi": formData.multipleChoice.score,//#多选题分数
              "bjsusepanduan": formData.enableTrueFalse === true? '1': '0',//#是否使用判断题
              "bjspanduan": formData.trueFalse.count,//#判断题数量
              "bjspanduanfenzhi": formData.trueFalse.score,//#判断题分数
              "bjsusejianda": formData.enableShortAnswer === true ? '1': '0',//#是否使用简答题
              "bjsjianda": formData.shortAnswer.count,//#简答题数量
              "bjsjiandafenzhi": formData.shortAnswer.score,//#简答题分数
              "bjslogo_uri": formData.apiImgCode,//#logo图片
              "bjsdesc": formData.saishijieshao,//#竞赛说明
              "bjstzgg": formData.tongzhigonggao,//#竞赛通知公告
            }).then(res => {
              console.log('赛事保存：',res);
              if(res.msg === '创建基础竞赛成功') {
                this.$router.push({
                  path: '/pro/index',
                  query: ''
                });
              } else {
                this.$message.success('赛事设置保存失败');
              }

            })

          } else {
            console.log('表单验证失败');
            return false;
          }
        });
      }

    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.eventForm = {
        name: '',
        timeRange: [],
        voteLimitPerDay: 10,
        voteLimitPerParticipant: 1,
        practiceBank: '',
        duration: 90,
        enableSingleChoice: true,
        singleChoice: {
          count: 80,
          score: 1
        },
        enableTrueFalse: true,
        trueFalse: {
          count: 10,
          score: 1
        },
        enableMultipleChoice: true,
        multipleChoice: {
          count: 10,
          score: 1
        },
        enableShortAnswer: true,
        shortAnswer: {
          count: 10,
          score: 1
        },
        coverImage: ''
      };
    }
  }
};
</script>

<style scoped>
.event-management-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.vote-rule {
  display: flex;
  align-items: center;
}

.question-settings {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.question-settings > * {
  margin-right: 10px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.uploader-placeholder i {
  font-size: 28px;
  margin-bottom: 10px;
}

</style>
